import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { Router } from "vue-router";

interface DynamicRoute {
  path: string;
  name: string;
  label: string;
  icon: string;
  url: string;
  meta : {
    name : string
  }
  component: () => Promise<any>;
  children: DynamicRoute[];
}
interface State {
  isCollapse: boolean;
  tags: Array<{ path: string; label: string; name: string; icon: string }>;
  currentMenu: null | any;
  menuList: DynamicRoute[];
  token: string;
  routerList: (() => void)[];
}
function initState(): State {
  return {
    isCollapse: false,
    tags: [
      {
        path: "/home",
        label: "首页",
        name: "home",
        icon: "house",
      },
    ],
    currentMenu: null,
    menuList: [],
    token: "",
    routerList: [],
  };
}

export const useAllDataStore = defineStore("allData", () => {
  const state = ref(initState());
  watch(
    state,
    (val) => {
      if (!val.token) return;
      localStorage.setItem("store", JSON.stringify(val));
    },
    { deep: true }
  );
  function selectTag(val: any) {
    if (val.name === "home") {
      state.value.currentMenu = null;
    } else {
      let index = state.value.tags.findIndex((item) => item.name === val.name);
      index === -1 ? state.value.tags.push(val) : "";
    }
  }
  function updateTag(val: any) {
    let index = state.value.tags.findIndex((item) => item.name === val.name);
    state.value.tags.splice(index, 1);
  }
  function updateMenuList(val: DynamicRoute[]) {
    state.value.menuList = val;
  }
  function addMenuList(router: Router, type: string) {
    if (type === "refresh") {
      let val = localStorage.getItem("store");
      if (val && JSON.parse(val)) {
        state.value = JSON.parse(val);
        state.value.routerList = [];
      } else {
        return;
      }
    }
    // 清空现有动态路由
    state.value.routerList.forEach((removeRoute) => removeRoute());
    state.value.routerList = [];

    const menu = state.value.menuList;
    const module = import.meta.glob("../views/**/*.vue");
    const routeArr: DynamicRoute[] = [];
    menu.forEach((item: DynamicRoute) => {
      if (item.children) {
        item.children.forEach((val) => {
          let url = `../views/${val.url}.vue`;
          val.component = module[url];
        });
        routeArr.push(...item.children);
      } else {
        let url = `../views/${item.url}.vue`;
        item.component = module[url];
        routeArr.push(item);
      }
    });
    routeArr.forEach((item) => {
      state.value.routerList.push(router.addRoute("main", item));
    });
  }
  function clean() {
    if (state.value.routerList.length)
      state.value.routerList.forEach((removeRoute) => {
        if(removeRoute) removeRoute();
      });
    state.value = initState();
    localStorage.removeItem("store")
  }
  return {
    state,
    selectTag,
    updateTag,
    updateMenuList,
    addMenuList,
    clean,
  };
});
